package cmd

import (
	"os"
	"os/exec"
	"path/filepath"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"github.com/spf13/cobra"
)

var (
	port    string
	tcpport string
	daemon  bool
)
var serverCmd = &cobra.Command{
	Use:     "server",
	Short:   "example:ims server port 8081",
	Example: "ims server -c config/",
	Run: func(cmd *cobra.Command, args []string) {
		run()
	},
}

func init() {
	serverCmd.Flags().StringVarP(&port, "port", "p", "8081", "监听端口号")
	serverCmd.Flags().StringVarP(&tcpport, "tcpport", "t", "8082", "监听tcp端口号")
	serverCmd.Flags().BoolVarP(&daemon, "daemon", "d", true, "是否为守护进程模式")
}

func run() {
	if daemon == true {
		if os.Getppid() != 1 {
			// 将命令行参数中执行文件路径转换成可用路径
			filePath, _ := filepath.Abs(os.Args[0])
			cmd := exec.Command(filePath, os.Args[1:]...)
			// 将其他命令传入生成出的进程
			cmd.Stdin = os.Stdin // 给新进程设置文件描述符，可以重定向到文件中
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			cmd.Start() // 开始执行新进程，不等待新进程退出
			os.Exit(0)
		}
	}

	s := g.Server()

	s.BindHandler("/", func(r *ghttp.Request) {
		r.Response.Write("哈喽世界！")
	})
	s.SetPort(gconv.Int(port))
	s.Run()
}
